package cn.wh.db.router.strategy.impl;



import cn.wh.db.router.DBRoutingConfig;
import cn.wh.db.router.bean.RoutingEntity;
import cn.wh.db.router.strategy.DBRoutingBase;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Author wh
 * @Description 默认的路由策略
 * @Date 2023/3/28 14:41
 * @Version 1.0
 **/
public class DefaultDBRouterStrategy extends DBRoutingBase {

    private Logger logger = LoggerFactory.getLogger(DefaultDBRouterStrategy.class);

    public DefaultDBRouterStrategy(DBRoutingConfig dbRoutingConfig) {
        super(dbRoutingConfig);
    }


    @Override
    protected RoutingEntity doRouting(String dbKey) {

        int size = super.dbRoutingConfig.getDbCount() * dbRoutingConfig.getTbCount();

        //扰动函数
        int idx = (size - 1) & (dbKey.hashCode() ^ (dbKey.hashCode() >>> 16));

        // 库表索引；相当于是把一个长条的桶，切割成段，对应分库分表中的库编号和表编号
        int dbIdx = idx / dbRoutingConfig.getTbCount() + 1;
        int tbIdx = idx - dbRoutingConfig.getTbCount() * (dbIdx - 1);

        logger.info("数据库路由 dbIdx:{},tbIdx:{}", dbIdx, tbIdx);
        return RoutingEntity
                .builder()
                .tbIdx(String.format("%03d",tbIdx))  //格式化路由
                .dbIdx(String.format("%02d",dbIdx))  //格式化路由
                .build();
    }
}
